

//
//  ConversationDetailCell.m
//  LookScore
//
//  Created by wws on 2018/1/24.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import <UIImageView+WebCache.h>
#import "ConversationDetailCell.h"
#import "SDPhotoBrowser.h"
@interface ConversationDetailCell(){
    
    //话题图片显示
    ConversationIssuePhotoView *_picContainerView;
    //加入用户头像
    UIImageView *_heraderImageView;
    //话题内容
    UILabel *_contentLable;
    //用户昵称
    UILabel *_nickNameLable;
    //关注按钮
    UIButton *_gzButton;
    
    
    //话题详细时间
    UILabel *_topicTimeLable;
    //浏览人数
    UIButton *_browseNumberButton;
    //点赞人数
    UIButton *_praiseNumberButton;
    //点赞按钮
    UIButton *_fabulousButton;
    
    UIButton *_topicBtn;
    
    UILabel * _additionalLable;
}
@end


@implementation ConversationDetailCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


+(ConversationDetailCell *)ConversationDetailCellWidthTableView:(UITableView *)tableView{
    
    ConversationDetailCell *cell=[tableView dequeueReusableCellWithIdentifier:NSStringFromClass(self)];
    if (!cell) {
        cell=[[ConversationDetailCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass(self)];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    return cell;
}


-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self addConversationSubViews];
    }
    
    return self;
}


/*发布的内容详情*/
-(void)addConversationSubViews{
    
    //加入用户头像
    UIImageView *heraderImageView=[UIImageView new];
    _heraderImageView=heraderImageView;

    heraderImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickedImageView)];
    [heraderImageView addGestureRecognizer:tap];
    //用户昵称
    UILabel *nickNameLable=[UILabel new];
    nickNameLable.textColor=LSTitleGrayColor1;
    nickNameLable.font=LSFontSize15;
    _nickNameLable=nickNameLable;


    //话题内容
    UILabel *contentLable=[UILabel new];
    contentLable.numberOfLines=0;
    contentLable.textColor=[[UIColor blackColor] colorWithAlphaComponent:0.7];;
    contentLable.font=LSFontSize14;
    _contentLable=contentLable;

    //关注按钮
    UIButton *gzButton=[[UIButton alloc]init];
    gzButton.titleLabel.textColor=LSTitleWhiteColor;
    gzButton.titleLabel.font=LSFontSize10;
    [gzButton setImage:[UIImage imageNamed:@"attend"] forState:UIControlStateNormal];
    [gzButton setImage:[UIImage imageNamed:@"selectAttend"] forState:UIControlStateSelected];
    gzButton.layer.masksToBounds=YES;
    gzButton.layer.cornerRadius=8;
    _gzButton=gzButton;
    gzButton.selected=NO;
    [gzButton addTarget:self action:@selector(gzButtonSender:) forControlEvents:UIControlEventTouchUpInside];
    //sd布局
    [self.contentView sd_addSubviews:@[heraderImageView,nickNameLable,contentLable,gzButton]];
    //头像
    heraderImageView.sd_layout
    .widthIs(30)
    .heightEqualToWidth()
    .leftSpaceToView(self.contentView,LSSpaceLeftWidth1)
    .topSpaceToView(self.contentView, 12);
    //关注按钮
    gzButton.sd_layout
    .widthIs(55)
    .heightIs(24)
    .centerYEqualToView(heraderImageView)
    .rightSpaceToView(self.contentView, LSSpaceLeftWidth1);
    //昵称
    nickNameLable.sd_layout
    .leftSpaceToView(heraderImageView, 5)
    .centerYEqualToView(heraderImageView)
    .rightSpaceToView(gzButton, 5)
    .heightIs(20);
    //详情
    contentLable.sd_layout
    .topSpaceToView(heraderImageView,15)
    .leftEqualToView(heraderImageView)
    .rightEqualToView(gzButton)
    .autoHeightRatio(0);


    //话题图片显示
    ConversationIssuePhotoView *photoView=[ConversationIssuePhotoView new];
    photoView.refreshBlock = ^{
        if (self.refreshBlock) {
            self.refreshBlock();
        }
        
    };
    _picContainerView = photoView;
    

    //绿茵沙场
    UIButton *topicTypeButton=[UIButton new];
    [topicTypeButton setTitleColor:Color(253, 140, 53) forState:UIControlStateNormal];
    topicTypeButton.titleLabel.font=LSFontSize13;
    topicTypeButton.layer.cornerRadius=5;
    [topicTypeButton setTitle:@"绿茵沙场" forState:UIControlStateNormal];
    topicTypeButton.layer.masksToBounds=YES;
    topicTypeButton.layer.borderColor=Color(253, 140, 53).CGColor;
    topicTypeButton.layer.borderWidth=0.5f;
     _topicBtn = topicTypeButton;

    //话题详细时间
    UILabel *topicTimeLable=[[UILabel alloc]init];
    topicTimeLable.font=LSFontSize10;
    topicTimeLable.textColor=LSTitleGrayColor3;
    topicTimeLable.textAlignment=NSTextAlignmentLeft;
    _topicTimeLable=topicTimeLable;

    //浏览人数
    UIButton *browseNumberButton=[UIButton new];
    [browseNumberButton setTitleColor:LSTitleGrayColor3 forState:UIControlStateNormal];
    [browseNumberButton setImage:[UIImage imageNamed:@"ChatBrowse"] forState:UIControlStateNormal];
    browseNumberButton.titleLabel.font=LSFontSize10;
    [browseNumberButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -10)];
    _browseNumberButton=browseNumberButton;

    //点赞人数
    UIButton *praiseNumberButton=[UIButton new];
    [praiseNumberButton setTitleColor:LSTitleGrayColor3 forState:UIControlStateNormal];
    [praiseNumberButton setImage:[UIImage imageNamed:@"ChatPraise"] forState:UIControlStateNormal];
    praiseNumberButton.titleLabel.font=LSFontSize10;
    [praiseNumberButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -10)];
    _praiseNumberButton=praiseNumberButton;

    //sd布局
    [self.contentView sd_addSubviews:@[photoView,topicTypeButton,topicTimeLable,praiseNumberButton,browseNumberButton]];

    photoView.sd_layout
    .topSpaceToView(contentLable, 10)
    .leftEqualToView(heraderImageView);

    topicTypeButton.sd_layout
    .leftEqualToView(heraderImageView)
    .topSpaceToView(photoView,9)
    .widthIs(60)
    .heightIs(20);
    
    topicTimeLable.sd_layout
    .leftSpaceToView(topicTypeButton, 7)
    .centerYEqualToView(topicTypeButton)
    .heightIs(20);
    [topicTimeLable setSingleLineAutoResizeWithMaxWidth:180];
    praiseNumberButton.sd_layout
    .rightEqualToView(gzButton)
    .centerYEqualToView(topicTypeButton)
    .widthIs(60)
    .heightIs(25);
    
    browseNumberButton.sd_layout
    .rightSpaceToView(praiseNumberButton, 2)
    .topEqualToView(praiseNumberButton)
    .widthIs(60)
    .heightIs(25);


    //点赞按钮
    UIButton *fabulousButton=[UIButton new];
    [fabulousButton setTitleColor:Color(253, 140, 53) forState:UIControlStateNormal];
    fabulousButton.backgroundColor=Color(255, 223, 192);
    [fabulousButton setTitle:@"赞" forState:UIControlStateNormal];
    fabulousButton.layer.borderWidth=1;
    [fabulousButton addTarget:self action:@selector(thumbupAction:) forControlEvents:UIControlEventTouchUpInside];
    fabulousButton.titleLabel.textAlignment=NSTextAlignmentCenter;
    fabulousButton.layer.borderColor=Color(253, 140, 53).CGColor;
    fabulousButton.titleLabel.font=LSFontSize13;
    _fabulousButton=fabulousButton;

    //附加说明
    UILabel *additionalLable=[[UILabel alloc]init];
    additionalLable.font=LSFontSize13;
    additionalLable.textColor=Color(253, 140, 53);
    additionalLable.textAlignment=NSTextAlignmentCenter;
    additionalLable.text=@"给楼主点个赞吧";
    _additionalLable = additionalLable;
    //sd布局
    [self.contentView sd_addSubviews:@[fabulousButton,additionalLable]];
    fabulousButton.sd_layout
    .topSpaceToView(topicTypeButton, 25)
    .centerXEqualToView(self.contentView)
    .widthIs(46)
    .heightEqualToWidth();
    fabulousButton.sd_cornerRadiusFromWidthRatio=@0.5;
    
    additionalLable.sd_layout
    .leftEqualToView(self.contentView)
    .rightEqualToView(self.contentView)
    .heightIs(20)
    .topSpaceToView(fabulousButton, 4);
    
}


/*话题模型*/
-(void)setIssueModel:(ConversationIssueModel *)issueModel{
    
    _issueModel=issueModel;
    if (issueModel.ImgUrlStr.length <= 0) {
        _picContainerView.picPathStringsArray = @[];
        _picContainerView.hidden = YES;
        _topicBtn.sd_resetLayout
        .leftEqualToView(_contentLable)
        .topSpaceToView(_contentLable,9)
        .widthIs(60)
        .heightIs(20);
        
    }else{
        _picContainerView.hidden = NO;
        NSArray * imageArray = [issueModel.ImgUrlStr componentsSeparatedByString:@","];
        //话题图片展示
        _picContainerView.picPathStringsArray = imageArray;
        _topicBtn.sd_resetLayout
        .leftEqualToView(_heraderImageView)
        .topSpaceToView(_picContainerView,9)
        .widthIs(60)
        .heightIs(20);
    }
    
    
    //用户头像
    [_heraderImageView sd_setImageWithURL:[NSURL URLWithString:issueModel.UserHeadUrl] placeholderImage:[UIImage imageNamed:@"MineDefaultHead"] options:SDWebImageRefreshCached];
   
    
    //用户昵称
    _nickNameLable.text = issueModel.UserDisName;
    
    //话题内容
    _contentLable.text = issueModel.TopicContent;
    //话题详细时间
    _topicTimeLable.text = [issueModel.CreateTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    
    //浏览人数
    [_browseNumberButton setTitle:[NSString stringWithFormat:@"%ld",issueModel.IpReadCount] forState:UIControlStateNormal];
    
    //点赞人数按钮
    [_praiseNumberButton setTitle:[NSString stringWithFormat:@"%ld",issueModel.ThumbupCount] forState:UIControlStateNormal];
    [_topicBtn setTitle:issueModel.CircleName forState:UIControlStateNormal];
    if (issueModel.IsAttended) {
        _gzButton.selected = YES;
    }else{
        _gzButton.selected = NO;
    }
    
    if (![LSAccountArchive isLogin]) {
        _gzButton.hidden = NO;
    }else{
        if ([[LSAccountArchive account].Cid isEqualToString:issueModel.UserCid]) {
            _gzButton.hidden = YES;
        }else{
            _gzButton.hidden = NO;
        }
    }
    
    [self setupAutoHeightWithBottomView:_additionalLable bottomMargin:30];
    
}

/*关注按钮*/
- (void)gzButtonSender:(UIButton *)sender{
//    sender.selected=!sender.selected;
    if ([_delegate respondsToSelector:@selector(gzButtonSender:)]) {
        [_delegate gzButtonSender:sender];
    }
    
    
}
/**点赞按钮*/
- (void)thumbupAction:(UIButton *)sender{
    if ([_delegate respondsToSelector:@selector(thumbupAction:)]) {
        [_delegate thumbupAction:sender];
    }
}

- (void)clickedImageView{
    if (self.block) {
        self.block();
    }
    
}

@end

#pragma mark-- ConversationIssuePhotoView

@interface ConversationIssuePhotoView ()<SDPhotoBrowserDelegate>

@property (nonatomic, strong) NSArray *imageViewsArray;

@end

@implementation ConversationIssuePhotoView{
    
    NSMutableArray * temHeightArray;
    
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
//        self.backgroundColor=[UIColor redColor];
        [self setup];
    }
    return self;
}

- (void)setup{
    NSMutableArray *temp = [NSMutableArray new];
    
    for (int i = 0; i < 9; i++) {
        UIImageView *imageView = [UIImageView new];
        [self addSubview:imageView];
//        imageView.contentMode = UIViewContentModeScaleAspectFill;
//        imageView.clipsToBounds = YES;
        imageView.userInteractionEnabled = YES;
        imageView.tag = i;
        imageView.frame = CGRectMake(0, 0, LSScreenWidth - 20, 200);
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapImageView:)];
        [imageView addGestureRecognizer:tap];
        [temp addObject:imageView];
    }
    
    self.imageViewsArray = [temp copy];
}


- (void)setPicPathStringsArray:(NSArray *)picPathStringsArray{
    _picPathStringsArray = picPathStringsArray;
    
    for (long i = _picPathStringsArray.count; i < self.imageViewsArray.count; i++) {
        UIImageView *imageView = [self.imageViewsArray objectAtIndex:i];
        imageView.hidden = YES;
    }
    
    if (_picPathStringsArray.count == 0) {
        self.height_sd = 0;
        self.fixedHeight = @(0);
        return;
    }
    
//    CGFloat itemW = [self itemWidthForPicPathArray:_picPathStringsArray];
    CGFloat __block itemW = 0;
    CGFloat __block itemH = 0;
    if (_picPathStringsArray.count == 1) {
        
        UIImageView * imageView = [[UIImageView alloc] init];
        [imageView sd_setImageWithURL:[NSURL URLWithString:_picPathStringsArray.firstObject] placeholderImage:nil];
        itemH = [self itemSizeForImageView:imageView].height;
        itemW = [self itemSizeForImageView:imageView].width;
    } else {

    }

    temHeightArray = @[].mutableCopy;
    __block CGFloat topicViewHeight = .0f;
    
    KWeakSelf(self);
    [_picPathStringsArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView * imageView = [_imageViewsArray objectAtIndex:idx];
        imageView.hidden = NO;
        NSString *urlStr = [obj stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];;

//        MyLog(@"开始");
//        [imageView]
        [imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil options:SDWebImageRetryFailed completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
            if (image.size.width > 0) {
                CGFloat height = (LSScreenWidth -20) / (image.size.width/image.size.height);
                imageView.frame = CGRectMake(0, topicViewHeight , LSScreenWidth-20, height);
                topicViewHeight += height+5;
                MyLog(@"走了这个方法");
               
                //等前面的异步操作都执行完毕后，回到主线程.
                self.width = LSScreenWidth-20;
                self.height = topicViewHeight;
                self.fixedHeight = @(topicViewHeight);
                self.fixedWidth = @(LSScreenWidth - 20);
                weakself.refreshBlock();
            }
//            if (image) {
//                
//            }
            MyLog(@"imageViewH = %.f",topicViewHeight);
        }];
//
    }];

//    MyLog(@"刷新");
//    [self createImg];

}
- (void)createImg{
    CGFloat itemH = 0;
    for (int i = 0; i < _picPathStringsArray.count ; i ++){
        //根据tag取出图片的imageView
        UIImageView * imgView = (UIImageView *)[self viewWithTag:i];
        if([temHeightArray[i] integerValue]>0){
            //高度赋值
            imgView.height = [temHeightArray[i] floatValue];
            MyLog(@"imgViewH = %.2f",imgView.height);
        }
        //根据图片的高度调整各图片的位置(纵坐标y)
        for (int j = i+1;j < _picPathStringsArray.count + 1; j++ ){
            UIImageView * tmpImgView = (UIImageView *)[self viewWithTag:j];
            tmpImgView.y = imgView.bottom + 5;
            MyLog(@"tmpy=%.2f",tmpImgView.y);
        }
        if (i == _picPathStringsArray.count - 1){
            //整个view的高度等于最后一张图片的下边界Y值
            itemH = imgView.bottom;
        }
    }
        self.width = LSScreenWidth-20;
        self.height = itemH;
    
        self.fixedHeight = @(itemH);
        self.fixedWidth = @(LSScreenWidth - 20);
    
}

/*图片点击tapImageView */
- (void)tapImageView:(UITapGestureRecognizer *)tap{
    UIView *imageView = tap.view;
//    if (_tapSeletedPhotoBlcok) {
//        _tapSeletedPhotoBlcok(imageView.tag);
//    }
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.currentImageIndex = imageView.tag;
    browser.sourceImagesContainerView = self;
    browser.imageCount = self.picPathStringsArray.count;
    browser.delegate = self;
    [browser show];
}


- (CGFloat)itemSizeForPicPathArray:(NSArray *)array{
    if (array.count == 1) {
        return 120;
    } else {
        CGFloat w = [UIScreen mainScreen].bounds.size.width > 320 ? 80 : 70;
        return w;
    }
}


- (CGSize)itemSizeForImageView:(UIImageView *)imageView{
    CGFloat itemW = 0;
    CGFloat itemH = 0;
    if (imageView.image.size.width) {
        //            itemH = imageView.image.size.height / imageView.image.size.width * itemW;
        if (imageView.image.size.width > LSScreenWidth - 20) {
            itemW = LSScreenWidth - 20;
            if (imageView.image.size.width > imageView.image.size.height) {
                itemH = imageView.image.size.height / imageView.image.size.width * itemW;
            }else{
                itemH = imageView.image.size.height;
            }
        }else{
            itemW = imageView.image.size.width;
            itemH = imageView.image.size.height;
        }
        
    }
//    if (sizeType == 1) {
//        return itemW;
//    }else{
//        return itemH;
//    }
    return CGSizeMake(itemW, itemH);
}
- (NSInteger)perRowItemCountForPicPathArray:(NSArray *)array{
    if (array.count < 3) {
        return array.count;
    } else if (array.count <= 4) {
        return 2;
    } else {
        return 3;
    }
}

#pragma mark - SDPhotoBrowserDelegate

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    NSString *imageName = self.picPathStringsArray[index];
    NSURL *url = [[NSBundle mainBundle] URLForResource:imageName withExtension:nil];
    return url;
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    UIImageView *imageView = self.subviews[index];
    return imageView.image;
}
@end
